﻿namespace UsageTracker.Service
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Diagnostics;
    using System.Reflection;
    using System.ServiceProcess;
    using System.Web.Http;
    using System.Web.Http.Dispatcher;
    using System.Web.Http.SelfHost;
    using log4net;
    using UsageTracker.Server;

    public partial class UsageCapture : ServiceBase
    {
        private readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        HttpSelfHostServer server = null;

        /// <summary>
        /// 
        /// </summary>
        public UsageCapture()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            this.StartListener();
        }

        /// <summary>
        /// 
        /// </summary>
        public void StartListener()
        {
            this.log.Info("Starting the Logging ReST listener.");
            try
            {
                var RestEndpoint = ConfigurationManager.AppSettings.Get("REST_SERVICE_URI");
                var config = new HttpSelfHostConfiguration(RestEndpoint);

                this.log.Info("Trying to initialize the external assemblies resolver.");

                //Initiate external WEBAPI controllers loading 
                config.Services.Replace(typeof(IAssembliesResolver), new ExtControllerResolver());

                config.Routes.MapHttpRoute("API Default", "api/{controller}", new { UsageTelemetryData = RouteParameter.Optional });
                this.server = new HttpSelfHostServer(config);
                this.server.OpenAsync().Wait();
                this.log.Info("ReST listener endpoint set as: " + RestEndpoint);
            }
            catch (Exception exp)
            {
                throw;
                //this.log.Fatal("The ReST listener service could not be started due to an error. Details - " + exp.Message);
                //this.log.Fatal(exp.StackTrace);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        protected override void OnStop()
        {
            this.log.Info("Shutting down the Logging ReST listener.");
            try
            {
                if (this.server != null)
                {
                    this.server.Dispose();
                }
            }
            catch (Exception exp)
            {
                this.log.Fatal("The ReST listener service could not shut down properly due to an error. Details - " + exp.Message);
                this.log.Fatal(exp.StackTrace);
            }
        }
    }
}
